<template>
  <div class="user-list">
    <div v-for="(u,i) in users" :key="u.id" class="user">
      <span>{{ i + 1 }}</span>
      <span>{{ u.name }}</span>
      <span>{{ u.gender }}</span>
      <span>{{ u.birthdate }}</span>
      <span>
        <router-link :to="{ name: 'edit' , query: { id: u.id } }">编辑</router-link>
        &nbsp;&nbsp;
        <a @click="remove(u.id)">删除</a>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserList',
  data(){
    return {
      users:[]
    }
  },
  // 生命周期钩子
  beforeMount(){
    let promise = this.axios.get('/apis/user/list');
    promise.then( res => {
      console.log( res );
      if( res.data.status === 'success' ) {
        this.users = res.data.users ;
      }
    }).catch( reason => {
      console.log( reason );
    });
  },
  methods: {
    remove(userid){
      console.log(userid);
      let promise = this.axios.delete(`/apis/user/remove/${userid}`);
      promise.then( res => {
        if( res.data.status === 'success' ){
          alert('删除成功');
          // 随后可以重新加载用户列表(即重新发起异步请求查询用户列表)
          // 也可以将 `this.users` 数组中指定 userid 对应的 user 删除
          let index = this.users.findIndex( u => u.id == userid );
          this.users.splice( index , 1 );
        }
      })
    }
  }
}
</script>

<style scoped>
.user-list {
  margin: 15px auto;
  border: 1px solid blue ;
}
.user{
  display: flex;
  margin: 10px;
  border: 1px solid gainsboro;
}
.user>span {
  flex-basis: 20%;
  text-align: center;
}

.user>span a {
  cursor: pointer;
  text-decoration: underline;
  color: blue ;
}
</style>